
export default {
  data() {
    return {
      loading: true, // loading
      queryObj: {
        // 查询所需参数
        pageSize: 10, // 默认每页展示10条
        pageNum: 1
      },
      totalSize: 0, // 总数
      dialogObj: {
        // dialog相关
        dialogTitle: {
          // 标题
          add: '新增',
          update: '编辑',
          check: '查看',
          delete: '删除'
        },
        dialogVisible: false, // 控制dialog显示
        dialogType: 'add' // 用于点击新增或者编辑等按钮的type
      },
      tableData: [], // 表格data
      tabClickName: 'first', // tab切换
      deleteToast: '删除'
    };
  },
  beforeRouteLeave(to, from, next) {
    // 每次切换路由销毁富文本，防止不显示bug
    /* eslint-disable no-undef */
    if (tinyMCE.activeEditor) {
      /* eslint-disable no-undef */
      tinyMCE.activeEditor.destroy();
    }
    next();
  },
  methods: {
    // 查询
    async queryData() {
      let resObj = '';
      this.loading = true;
      this.dialogObj.dialogVisible = false;
      await this.queryApi({
        ...this.queryObj
      })
        .then(res => {
          if (res.code === '200') {
            this.tableData = res.data.pageData;
            this.totalSize = res.data.totalSize;
            resObj = res.data;
          }
        })
        .finally(() => {
          this.loading = false;
        });
      return Promise.resolve(resObj);
    },
    // 查询单个，编辑/查看
    async queryDataById(id) {
      let resObj = '';
      await this.queryByIdApi({
        id
      }).then(res => {
        if (res.code === '200') {
          resObj = res.data;
          this.formObj = res.data;
          this.dialogObj.dialogVisible = true;
        }
      });
      return Promise.resolve(resObj);
    },
    // 删除
    async deleteData(id) {
      await this.$confirm(
        `是否${this.deleteToast}该${this.toastTitle}？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(async() => {
          await this.deleteApi({
            id
          }).then(res => {
            if (res.code === '200') {
              this.$message.success(
                `${this.deleteToast}${this.toastTitle}成功`
              );
              this.queryData();
            }
          });
        })
        .catch(() => {});
      return Promise.resolve();
    },
    // 批量删除
    async deleteDataMuilty() {
      const { ids } = this;
      if (!ids.length) {
        return this.$message.error(
          `请选择需要${this.deleteToast}的${this.toastTitle}`
        );
      }
      await this.$confirm(
        `是否批量${this.deleteToast}所选中${this.toastTitle}？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(async() => {
          await this.deleteMuiltApi({
            ids
          }).then(res => {
            if (res.code === '200') {
              this.$message.success(
                `批量${this.deleteToast}${this.toastTitle}成功`
              );
              this.queryData();
            }
          });
        })
        .catch(() => {});
      return Promise.resolve();
    },
    // 批量启用禁用 0启用，1禁用
    async updateStatusMuilty(status) {
      const { ids } = this;
      const statusObj = {
        ids,
        status
      };
      if (!ids.length) {
        return this.$message.error(
          `请选择需要${status === 0 ? '启用' : '禁用'}的${this.toastTitle}`
        );
      }
      await this.$confirm(
        `是否批量${status === 0 ? '启用' : '禁用'}所选中${this.toastTitle}？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(async() => {
          await this.updateStatusMuiltApi({
            ...statusObj
          }).then(res => {
            if (res.code === '200') {
              this.$message.success(
                `批量${status === 0 ? '启用' : '禁用'}${this.toastTitle}成功`
              );
              this.queryData();
            }
          });
        })
        .catch(() => {});
      return Promise.resolve();
    },
    // 执行新增
    async addData() {
      this.deleteKey();
      delete this.formObj.id;
      await this.$confirm(`是否新增${this.toastTitle}？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await this.addApi({
            ...this.formObj
          })
            .then(res => {
              if (res.code === '200') {
                this.$message.success(`新增${this.toastTitle}成功`);
                this.queryData();
              }
            })
            .finally(() => {
              this.dialogClose();
            });
        })
        .catch(() => {});
    },
    // 执行编辑
    async updateData() {
      this.deleteKey();
      await this.$confirm(`是否更新${this.toastTitle}？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await this.updateApi({
            ...this.formObj
          })
            .then(res => {
              if (res.code === '200') {
                this.$message.success(`更新${this.toastTitle}成功`);
                this.queryData();
              }
            })
            .finally(() => {
              this.dialogClose();
            });
        })
        .catch(() => {});
      return Promise.resolve();
    },

    // 修改状态 status 0 启用，1禁用
    async updateStatus(id, status) {
      await this.$confirm(
        `是否修改状态为${status === 0 ? '启用' : '禁用'}`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(async() => {
          await this.updateStatusApi({
            id,
            status
          })
            .then(res => {
              if (res.code === '200') {
                this.$message.success(
                  `${status === 0 ? '启用' : '禁用'}${this.toastTitle}成功`
                );
                this.queryData();
              }
            })
            .finally(() => {
              this.dialogClose();
            });
        })
        .catch(() => {});
      return Promise.resolve();
    },
    // 删除多余key
    deleteKey() {
      const keyArr = [];
      for (const initKey in this.$options.data().formObj) {
        keyArr.push(initKey);
      }
      for (const fromKey in this.formObj) {
        if (!keyArr.includes(fromKey)) {
          delete this.formObj[fromKey];
        }
      }
    },
    // 保存信息
    saveInfo() {
      this.$refs.dialog.$refs.formObj.validate(valid => {
        if (valid) {
          if (this.dialogObj.dialogType === 'add') {
            this.addData(); // 执行新增
          } else if (this.dialogObj.dialogType === 'update') {
            this.updateData(); // 执行更新
          }
        } else {
          this.$message.error('请完善表单信息');
          return false;
        }
      });
    },
    // 操作栏点击
    handleCommand(command, scope) {
      this.dialogObj.dialogType = command;
      switch (command) {
        case 'update':
          this.queryDataById(scope.row.id);
          break;
        case 'check':
          this.queryDataById(scope.row.id);
          break;
        case 'delete':
          this.deleteData(scope.row.id);
          break;
        case 'enable':
          this.updateStatus(scope.row.id, 0);
          break;
        case 'disable':
          this.updateStatus(scope.row.id, 1);
          break;
      }
    },
    // 导出excel
    exportExcel() {},
    // 重置表单数据
    resetData() {
      this.$nextTick(() => {
        this.formObj = this.$options.data().formObj; // 重置dialog表单
        // Object.assign(this.$data, this.$options.data())
        this.loading = false; // 初始化loading
        setTimeout(() => {
          this.$refs.main.$refs.multipleTable.clearSelection(); // 清除表格数据选中状态
          this.$refs.dialog.$refs.formObj.clearValidate(); // 清除验证
          this.dialogObj.dialogType = 'add'; // 初始化dialog
        }, 200);
      });
    },
    // 点击搜索
    handleSearch() {
      this.queryData();
    },
    // 取消选择
    toggleSelection() {
      this.$refs.main.$refs.multipleTable.clearSelection();
    },
    // 分页改变
    pageChange(val) {
      this.queryObj.pageNum = val;
      this.queryData();
    },
    dialogClose() {
      this.resetData();
      this.dialogObj.dialogVisible = false;
    },
    dialogOpen() {
      this.resetData();
      this.dialogObj.dialogVisible = true;
    }
  }
};
